<route type="page" lang="json5">
{
  style: { navigationStyle: 'custom' }
}
</route>

<template>
  <view class="full-page" :style="{ paddingTop: safeArea.top + 'px', paddingBottom: safeArea.bottom + 'px' }">
    <view>
      <view class="wraper">
        <wd-sidebar v-model="active" @change="handleChange">
          <wd-sidebar-item v-for="(item, index) in categories" :key="index" :value="index" :label="item.categoryName" />
        </wd-sidebar>

        <scroll-view
          class="content"
          scroll-y
          scroll-with-animation
          :scroll-top="scrollTop"
          :throttle="false"
          @scroll="onScroll"
        >
          <view v-for="(item, index) in categories" :key="index" class="category">
            <wd-cell-group :title="item.categoryName" border>
              <!--  固定高度200rpx  -->
              <wd-card class="goods-card" style="" v-for="(cell, index) in item.goodsInfoVoList" :key="index">
                <!--  在goods-card内横向纵向居中 -->
                <view class="goods-container">
                  <!-- 商品图片，在goods-container最左侧，距离goods-container有14rpx左边距，宽度在goods-container内35%，内容横向纵向居中   -->
                  <view class="goods-img">
                    <wd-img :width="75" :height="75" :src="cell.goodsImgUrl" />
                  </view>
                  <view class="goods-info">
                    <view class="goods-name">{{ cell.goodsName }}</view>
                    <view class="goods-desc">{{ cell.goodsDescription || '好喝' }}</view>
                  </view>
                  <view class="goods-price">￥{{ cell.goodsPrice }}</view>
                  <!--  加入购物车按钮，圆形，图标在add-cart 中横向纵向居中 -->
                  <view class="add-cart-btn" @click="addShoppingCart(cell)">
                    <wd-icon name="add" style="color: black; font-size: 20rpx" />
                  </view>
                </view>
              </wd-card>
            </wd-cell-group>
          </view>
        </scroll-view>
      </view>
    </view>

    <view class="cart-popup">
      <!--  购物车弹出栏  -->
      <wd-popup
        v-model="shoppingCartShow"
        position="bottom"
        :safe-area-inset-bottom="true"
        custom-style="height: 300px;"
        @close="handleClose"
        custom-class="custom-popup"
      >
        <!-- 关闭按钮 -->
        <view class="close">
          <wd-button type="icon" icon="close" size="small" @click="handleClose"></wd-button>
        </view>
        <!-- 如果没有选购 -->
        <view v-if="cartNum == 0">
          <view class="no-goods-img">
            <wd-img :width="200" :height="200" :src="noGoodsImg" />
            <view>什么页没有</view>
          </view>
        </view>
        <!-- 购物车商品列表 -->
        <view class="shopping-cart-list" v-if="cartNum > 0">
          <view
            class="shopping-cart-item"
            v-for="(item, index) in shoppingCartList"
            :key="index"
            style="
              background-color: #fdfaf0;
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin: 30rpx;
            "
          >
            <view style="text-align: left">{{ item.goodsName }}</view>
            <view style="text-align: center">
              <wd-input-number v-model="item.quantity" :min="0" @change="handleGoodsQuantityChange(item)" />
            </view>
            <view style="text-align: right">￥{{ item.goodsPrice * item.quantity }}</view>
          </view>

          <view class="shopping-cart-place-order">
            <view>
              <!-- 左侧 粉色 填充占宽度30% -->
              <view class="shop-icon">
                <wd-icon name="shop" style="font-size: 50rpx" />
              </view>
              <!--  中间  -->
              <view class="cart-total-price">总计 ￥：{{ cartTotalPrice }}</view>
              <!--  右侧 -->
              <view class="to-place-order">
                <wd-button size="small" custom-class="place-order-btn" @click="toPlaceOrder">下单</wd-button>
              </view>
            </view>
          </view>
        </view>
      </wd-popup>
    </view>

    <!-- 购物车悬浮按钮  -->
    <view class="shopping-cart-btn" v-if="!shoppingCartShow">
      <wd-fab :draggable="true">
        <template #trigger>
          <wd-badge :modelValue="cartNum">
            <wd-button type="icon" icon="cart" size="large" custom-class="fab-btn" @click="shoppingCartOpen()" />
          </wd-badge>
        </template>
      </wd-fab>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getRect, isArray } from 'wot-design-uni/components/common/util'
import { GoodsVo, MenuGoodsItemVo } from '@/api/menu/goods'
import { getMenuGoodsListApi } from '@/api/menu'
import { useShoppingCartStore } from '@/store/shoppingCart'
import { WorkOrderVo } from '@/api/menu/shoppingCart'
import noGoodsImg from "@/static/images/menu/no-goods.png";


// 定义安全区域信息的响应式变量
const safeArea = ref({
  top: 0,
  bottom: 0
})

const active = ref<number>(1)
const scrollTop = ref<number>(0)
const itemScrollTop = ref<number[]>([])

// 定义 categories 为 MenuGoodsItemVo 类型的数组
const categories = ref<MenuGoodsItemVo[]>([])
const getCategories = () => {
  getMenuGoodsListApi().then(res => {
    categories.value = res.data
    nextTick(() => {
      getRect('.category', true).then(rects => {
        if (isArray(rects)) {
          itemScrollTop.value = rects.map(item => item.top || 0)
          scrollTop.value = rects[active.value].top || 0
        }
      })
    })
  })
}

//缓存
const shoppingCartStore = useShoppingCartStore()

//购物车商品数量
const cartNum = ref<number>()

//购物车总价
const cartTotalPrice = ref<number | string>()

//商品列表
const shoppingCartList = ref<WorkOrderVo[]>([]) // 确保初始化为空数组

//
const addShoppingCart = (goods: GoodsVo) => {
  // 将商品信息添加到购物车列表
  shoppingCartStore.addToCart({
    goodsId: goods.goodsId,
    goodsName: goods.goodsName,
    goodsPrice: goods.goodsPrice
  })

  // 获取购物车商品列表
  shoppingCartList.value = shoppingCartStore.getCartItems
  // 获取购物车总数量
  cartNum.value = shoppingCartStore.getCartTotalItems
  //
  cartTotalPrice.value = shoppingCartStore.getCartTotalPrice.toFixed(2)
}

//获取购物车信息
const getShoppingCart = () => {
  shoppingCartList.value = shoppingCartStore.getCartItems
  cartNum.value = shoppingCartStore.getCartTotalItems
  cartTotalPrice.value = shoppingCartStore.getCartTotalPrice
}

const shoppingCartShow = ref(false)

function shoppingCartOpen() {
  shoppingCartShow.value = true
}

function handleClose() {
  shoppingCartShow.value = false
}

onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  // 设置安全区域信息
  safeArea.value = {
    top: systemInfo.safeAreaInsets.top,
    bottom: systemInfo.safeAreaInsets.bottom
  }
  getCategories()
  getShoppingCart()
})

// 跳转订单结算界面
const toPlaceOrder = () => {
  uni.navigateTo({ url: '/pages/menu/place-order' })
}

function handleChange({ value }) {
  active.value = value
  scrollTop.value = itemScrollTop.value[value]
}

function handleGoodsQuantityChange(goods) {
  shoppingCartStore.updateQuantity(goods.goodsId, goods.quantity)
  getShoppingCart()
}

function onScroll(e) {
  const { scrollTop: currentScrollTop } = e.detail
  const threshold = 50 // 下一个标题与顶部的距离
  if (currentScrollTop < threshold) {
    active.value = 0
    return
  }
  const index = itemScrollTop.value.findIndex(top => top > currentScrollTop && top - currentScrollTop <= threshold)
  if (index > -1) {
    active.value = index
  }
}
</script>

<style lang="scss" scoped>
html,
body {
  margin: 0;
  padding: 0;
}
.full-page {
  background-color: #fbece5;
  height: 100vh;
}

.wraper {
  border-radius: 25rpx;
  display: flex;
  height: calc(100vh - var(--window-top));
  height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom));
  height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));

  :deep() {
    .uni-scroll-view-content {
      background-color: #fbece5;
    }

    .wd-sidebar-item--active {
      color: #f69947;
      background-color: #fdfaf0;
    }

    .wd-cell-group__title {
      background-color: #fbece5;
    }

    .wd-cell-group__body {
      background-color: #fbece5;
    }

    .wd-sidebar-item--active::before {
      background-color: #fbece5;
    }

    .wd-sidebar-item__badge {
      font-size: 85%;
    }

    .wd-icon wd-popup__close wd-icon-add {
      display: block;
    }
  }
}

.cart-popup {
  :deep() {
    .custom-popup {
      background-color: #fdfaf0;
    }
  }
}

.goods-card {
  height: 180rpx;
  padding: 20rpx;

  .goods-container {
    height: 180rpx;
    display: flex;
    align-items: center;
    position: relative;

    .goods-img {
      margin-left: 1%;
      width: 35%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .goods-info {
      width: 40%;
      margin: 0% 5% 0% 2%;

      .goods-name {
        color: #000000;
      }

      .goods-desc {
        margin-top: 5%;
        font-size: 24rpx;
      }
    }

    .goods-price {
      position: absolute;
      right: 3%;
      top: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: black;
    }

    .add-cart-btn {
      background-color: #fbece5;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      position: absolute;
      right: 20rpx;
      bottom: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.shopping-cart-btn {
  :deep() {
    .fab-btn {
      background-color: #ffb9c5;
      border-radius: 50%; // 添加这行代码将按钮变为圆形
      width: 100rpx;
      height: 100rpx;
    }
  }
}

.shopping-cart-place-order {
  width: 96%;
  height: 10%;
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: white;
  border-top: 2rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  border-radius: 50rpx;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.1);
  padding: 0 20rpx;
}

.shopping-cart-place-order .shop-icon {
  position: absolute;
  display: flex;
  left: 4%;
  align-items: center;
  min-width: 30%;
  justify-content: flex-start; /* 让图标靠左 */
  top: 45%;
  transform: translateY(-50%);
}

.shopping-cart-place-order .cart-total-price {
  position: absolute;
  left: 30%;
  top: 45%;
  transform: translateY(-50%);
}

.shopping-cart-place-order .to-place-order {
  position: absolute;
  right: 10%;
  top: 50%;
  transform: translateY(-50%);
}

.shopping-cart-place-order {
  :deep() {
    .place-order-btn {
      background-color: #ffb9c5;
    }
  }
}

.content {
  flex: 1;
  background: #fff;
}
</style>
